package apig.server;

import java.sql.*;
import java.util.*;

import org.h2.jdbcx.*;

import apii.algorithm.tokenizer.*;
import apii.dao.*;

/**
 * <b>Note:</b> Thread SAFE.
 * <p>
 * <b>Note:</b> Doesn't create threads.
 * 
 * @author Alex
 * 
 */
public class ServerThings {
	private static ServerThings things = null;
	

	public static synchronized ServerThings getThings() {
		if (things == null) {
			things = new ServerThings();
		}
		return things;
	}

	private final JdbcConnectionPool cp;
	private Dao dao;

	public Connection getConnection() throws SQLException {
		Connection c = cp.getConnection();
		try {
			c.setAutoCommit(false);
			try (Statement st = c.createStatement()) {
				st.execute("set schema apii");
			}
			return c;
		} catch (SQLException e) {
			c.close();
			throw e;
		}
	}
	
	public Dao getDao() {
		if (dao == null) {
			dao = new H2Dao();
		}
		return dao;
	}

	public List<? extends Tokenizer> getTokenizers() {
		return Collections.unmodifiableList(Arrays.asList(new Tokenizer() {

			@Override
			public Token[] parse(String code) throws MalformedCodeException {
				return null;
			}
		}));
	}

	private ServerThings() {
		cp = JdbcConnectionPool.create("jdbc:h2:~/apiidb/apiidb;MVCC=TRUE",
				"sa", "");
		cp.setLoginTimeout(100000000);
		cp.setMaxConnections(1000);
	}

	private void removeSessionData() {
		try {
			Connection c = getConnection();
			Statement s = c.createStatement();
			s.executeUpdate("DELETE FROM apii.user_session_data");
			c.commit();
			c.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

	void finish() {
		cp.dispose();
	}
}
